<template>
    <div class="threeJsPrc">
      <!-- Threejs第一个3D场景 -->
      <!-- 旋转动画、requestAnimationFrame周期性渲染 -->
      <canvas ref="myCanvas"></canvas>
    </div>
</template>

<script lang="ts">
import { Vue, Options } from 'vue-property-decorator';
import * as Three from 'three';
@Options({ components: {
} })
export default class ThreeJsPrc extends Vue {
  public rect!: DOMRect;
  public scene!:  Three.Scene ;
  public geometry!: Three.BoxGeometry;
  public material!: Three.MeshLambertMaterial;
  public mesh!: Three.Mesh;
  public camera!: Three.OrthographicCamera;
  public renderer!: Three.WebGLRenderer;
  public t0!: Date;
  public t1!: Date;
  public t!: number;


  public draw() {
    this.t1 = new Date();
    this.t = this.t1.getTime() - this.t0.getTime();
    this.t0 = this.t1;
    this.renderer.render(this.scene, this.camera);
    this.mesh.rotateX(0.001 * this.t);
    this.mesh.rotateY(0.001 * this.t);
    this.mesh.rotateZ(0.001 * this.t);

    requestAnimationFrame(() => {
      this.draw();
    });
  }
  public mounted() {
    this.rect = (this.$el as HTMLElement).getBoundingClientRect();
    // 场景
    this.scene = new Three.Scene();
    this.geometry = new Three.BoxGeometry(100, 100, 100);
    this.material = new Three.MeshLambertMaterial({
      color: 0x00ff00,
    });
    this.mesh = new Three.Mesh(this.geometry, this.material);
    this.scene.add(this.mesh);
    const point = new Three.PointLight(0xffffff);
    point.position.set(200, 200, 300);
    this.scene.add(point);
    const ambient = new Three.AmbientLight(0x4444);
    this.scene.add(ambient);

    // 相机
    this.camera = new Three.OrthographicCamera(
      -200 * this.rect.width / this.rect.height,
      200 * this.rect.width / this.rect.height,
      200, -200, 1, 1000,
    );
    this.camera.position.set(200, 100, 200);
    this.camera.lookAt(this.scene.position);

    // 渲染器
    const myCanvas = this.$refs.myCanvas as HTMLCanvasElement;
    this.renderer = new Three.WebGLRenderer({ canvas: myCanvas });
    this.renderer.setSize(this.rect.width, this.rect.height);
    this.renderer.setClearColor(0xb9d3ff, 1);

    this.t0 = new Date();
    this.draw();
  }
}
</script>

<style lang="postcss" scoped>
.threeJsPrc{touch-action: none;
  width: 100%;
  height: 100%;
  background: grey;
}
</style>
